import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { CreateTagDto } from './dto/create-tag.dto';
import { UpdateTagDto } from './dto/update-tag.dto';
import { Tag } from './entities/tag.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ArticleTag } from '../common/entities/article-tag.entity';

@Injectable()
export class TagsService {
  constructor(
    @InjectRepository(Tag)
    private readonly tagsRepository: Repository<Tag>,
    @InjectRepository(ArticleTag)
    private readonly articleTagRepository: Repository<ArticleTag>,
  ) {}

  async create(createTagDto: CreateTagDto) {
    const { label } = createTagDto;
    const hasTag = await this.tagsRepository.findBy({ label });
    if (hasTag.length > 0) throw new HttpException(`标签 #${label} 已存在`, HttpStatus.CONFLICT);
    const category = this.tagsRepository.create({ ...createTagDto });
    return this.tagsRepository.save(category);
  }

  async findAll() {
    return await this.tagsRepository.find();
  }

  async update(id: number, updateTagDto: UpdateTagDto) {
    const tag = await this.tagsRepository.preload({ id, ...updateTagDto });
    if (!tag) throw new HttpException(`未找到标签 #${id}`, HttpStatus.NOT_FOUND);
    return this.tagsRepository.save(tag);
  }

  async remove(id: number) {
    const hasTag = await this.tagsRepository.findBy({ id });

    if (hasTag.length === 0) throw new HttpException(`未找到标签 #${id}`, HttpStatus.NOT_FOUND);

    const isTagAssociated = await this.articleTagRepository.count({
      where: { tagId: id },
    });
    if (isTagAssociated > 0) throw new HttpException(`标签 #${id} 已被关联，无法删除`, HttpStatus.BAD_REQUEST);

    await this.tagsRepository.delete(id);
    return `删除成功`;
  }
}
